Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
function showLoading() {
    const url = window._server + '/report-asserts/icons/loading.gif';
    const h = $(window).height() / 2, w = $(window).width() / 2;
    const cover = $(`<div class="ureport-loading-cover" style="position: absolute;left: 0px;top: 0px;width:${w * 2}px;height:${h * 2}px;z-index: 1199;background:rgba(222,222,222,.5)"></div>`);
    $(document.body).append(cover);
    const loading = $(`<div class="ureport-loading" style="text-align: center;position: absolute;z-index: 1120;left: ${w - 35}px;top: ${h - 35}px;"><img src="${url}">
    <div style="margin-top: 5px">打印数据加载中...</div></div>`);
    $(document.body).append(loading);
};

function hideLoading() {
    $('.ureport-loading-cover').remove();
    $('.ureport-loading').remove();
};

function mmtoPixel(MM) {
    var value = (MM * 72 ) / 25.4;
    var px = Math.round(value);
    return px;
}

function pixeltoMM(px) {
    var value = (px * 25.4) / 72;
    var mm = Math.round(value);
    return mm;
}

/**
 * 获取当前Series data中的itemstyle 适用于饼状图 漏斗图
 * @param seriesData
 * @param name
 * @returns {{color: string}}
 */
function getSeriesDataItemStyle(seriesData, name) {
    let itemStyle = {color: ''}
    for (let item of seriesData) {
        if (name === item.name) {
            itemStyle = item['itemStyle']
            break;
        }
    }
    return itemStyle;
}



function refreshChart(chartOption) {
    var chartId = chartOption.chartId;
    var option = chartOption.option;
    var chartType = chartOption.chartType;
    var dataSettings = chartOption.extData;
    var seriesConfig = option['series']
    var mychart = echarts.init(document.getElementById(chartId));
    if (dataSettings && dataSettings.dataId) {
        var url = window._server + "/report/design/runChart?dataSetId=" + dataSettings.dataId
        $.ajax({
            url,
            type: 'get',
            success: function (result) {
                var dataList = result.data
                let seriesTypeData = []
                // 对于单柱体 单折线  需要配置series内的name属性 tooltip展示的时候 用到
                if (option && option['series'] && option['series'].length == 1 && chartType.indexOf("bar.multi") == -1 && chartType != "line.multi" && chartType.indexOf("bar.stack") == -1) {
                    option['series'][0].name = dataSettings.yText
                }
                //柱体 折线
                if (chartType === 'bar.simple' || (chartType.indexOf('line.') !== -1 && chartType !== 'line.multi')) {
                    let {axisX, axisY} = dataSettings
                    let xarray = []
                    let yarray = []
                    for (let item of dataList) {
                        xarray.push(item[axisX])
                        yarray.push(item[axisY])
                    }
                    if (dataSettings['run'] === 1) {
                        xAxisSettings.data = xarray
                    }
                    option['xAxis']['data'] = xarray
                    seriesConfig[0].data = yarray
                }
                else if (chartType === 'scatter.simple') {
                    let {axisX, axisY} = dataSettings
                    let array = []
                    for (let item of dataList) {
                        array.push([item[axisX], item[axisY]])
                    }
                    seriesConfig[0].data = array
                }
                else if (chartType === 'scatter.bubble') {
                    let {axisX, axisY, series} = dataSettings
                    let seriesMap = {}
                    for (let item of dataList) {
                        //获取series数据
                        seriesMap[item[series]] = 1
                    }
                    let realSeries = []
                    let legendData = Object.keys(seriesMap)
                    let singleSeries = seriesConfig[0]
                    for (let i = 0; i < legendData.length; i++) {
                        let name = legendData[i]
                        let seriesData = []
                        let temparr = dataList.filter(item = > {
                                return item[series] == name
                            }
                    )
                        temparr.forEach(function (e) {
                            seriesData.push([e[axisX], e[axisY]])
                        })
                        let itemstyle = this.getSeriesItemStyle(seriesConfig, i, name)
                        let obj = Object.assign({},
                            singleSeries,
                            itemstyle, {
                                name: name,
                                data: seriesData,
                            })
                        realSeries.push(obj)
                    }
                    if (dataSettings['run'] === 1) {
                        this.legendSettings.data = legendData
                    }
                    option['legend']['data'] = legendData
                    option['series'] = realSeries
                }
                else if (chartType.indexOf('pie') != -1 || chartType === 'funnel.simple') {
                    debugger
                    let {axisX, axisY} = dataSettings
                    let ls = [], xarray = []
                    for (let item of dataList) {
                        let tempName = item[axisX]
                        let itemStyle = getSeriesDataItemStyle(seriesConfig[0].data, tempName)
                        ls.push({
                            name: tempName,
                            value: item[axisY],
                            itemStyle: itemStyle
                        })
                        xarray.push(item[axisX])
                    }
                    if (dataSettings['run'] === 1) {
                        this.legendSettings.data = xarray
                    }
                    option['legend']['data'] = xarray
                    seriesConfig[0].data = ls
                }

                mychart.setOption(option);
            }
        });
    } else {
        mychart.setOption(option);
    }
}

function createPaging() {
    var first = $(".first"), last = $(".last"), next = $(".next"), end = $(".end"), pageIndexValue = $(".pageIndex"), pageSizeValue = $(".pageSize");
    if (window.pageSize === 0) {
        return;
    }
    pageIndexValue.val(window.pageIndex + 1);
    pageSizeValue.html(window.pageSize)
    var urlParameters = buildLocationSearchParameters('pageIndex');
    var url = window._server + '/report/view' + urlParameters;


    if (window.pageIndex == 0) {
        first.attr("disabled", "true");
    } else {
        first.removeAttr("disabled");
    }
    if (window.pageSize > 0 && window.pageIndex < window.pageSize) {
        last.removeAttr("disabled");
        next.removeAttr("disabled");
        end.removeAttr("disabled");
    }
    if (window.pageIndex == window.pageSize - 1) {
        end.attr("disabled", "true");
        next.attr("disabled", "true");
    }
}

function pagingEvent() {
    var first = $(".first"), last = $(".last"), next = $(".next"), end = $(".end")
    first.click(function () {
        loadHtml({reportId: window.reportId, pageIndex: 0})
    });

    last.click(function () {
            if (window.pageIndex > 0) {
                loadHtml({reportId: window.reportId, pageIndex: (window.pageIndex - 1)})
            }
        }
    );

    next.click(function () {
            if (window.pageIndex < window.pageSize - 1) {
                loadHtml({reportId: window.reportId, pageIndex: (window.pageIndex + 1)})
            }
        }
    );

    end.click(function () {
        loadHtml({reportId: window.reportId, pageIndex: (window.pageSize - 1)})
    });
}

function getChartData() {
    var data = {};
    $('.chart').each(function (index, element) {
        var chartId = $(this).attr('id')
        var chartObj = echarts.getInstanceByDom($(this)[0])
        if (chartObj) {
            data[chartId] = chartObj.getDataURL()
        }
    })
    return data;
}

function loadHtml(param) {
    var $form = $(this)
    if (window.searchFormParameters) {
        $.extend(true, param, window.searchFormParameters)
    }
    param._ = new Date().getTime();
    const url = window._server + '/report/pageContent';
    showLoading();
    $.ajax({
        url,
        type: 'post',
        data: param,
        beforeSend: function (request) {
            let token = window.localStorage.getItem('report-Access-Token');
            if (token != null && token != "") {
                request.setRequestHeader(Bolt.tokenName, token);
            }
        },
        success: function (result) {
            const data = result.data;
            const html = data.pageContent;
            window.pageSize = data.pageSize;
            window.pageIndex = data.pageIndex;
            $('.bolt-report-sheet').html(html);
            createPaging();
            hideLoading();
        }
    });
}

$(document).ready(function () {
    let token = Bolt.getRequestUrl().token;
    if (token != null && token != "") {
        window.localStorage.setItem('report-Access-Token', token);
    }
    var query_container = $('.bolt-query-container');
    if (query_container) {
        var param_form = $('#query_form_' + reportId);
        // query_container.height(param_form.height() + 15);
        $('.bolt-report-sheet').height($(window).height() - param_form.height() - 45);
    }

    var dropdownList = $('div .dropdown-list');
    $.each(dropdownList, function (i, v) {
        var menuButton = $(v).parent();
        menuButton.on("mouseover", (function (e) {
            $(v).show()
        })).on("mouseout", (function (e) {
            $(v).hide()
        }))
    });
    pagingEvent()

    loadHtml({reportId: window.reportId, pageIndex: 0})

    $('form[data-toggle="searchReport"]').submit(function (e) {
        var $form = $(this);
        window.searchFormParameters = {};
        try {
            if ($form.valid()) {
                $.each($form.serializeArray(), function (i, field) {
                    var $select = $("select[name='" + field.name + "']")
                    if ($select.length > 0) {
                        window.searchFormParameters[field.name] = $select.selectpicker('val').toString();
                    } else {
                        window.searchFormParameters[field.name] = field.value;
                    }
                });
                loadHtml({reportId: window.reportId, pageIndex: 0});
            }
        } catch {
            e
        .
        preventDefault();
    }

        e.preventDefault();
    })

    $('#htmlPrint').click(function () {
        const urlParameters = buildLocationSearchParameters();
        const url = window._server + '/report/loadHtmlPrintPaper/' + window.reportId + urlParameters;
        showLoading();
        var data = getChartData();
        $.ajax({
            url,
            type: 'post',
            data: data,
            success: function (result) {
                hideLoading();
                const paper = result.data;
                const html = paper.content;
                const iFrame = window.frames['_print_frame'];
                let styles = `<style type="text/css">`;
                styles += buildPrintStyle(paper);
                styles += `</style>`;
                $(iFrame.document.body).html(styles + html);
                iFrame.window.focus();
                iFrame.window.print();
            },
            error: function (response) {
                hideLoading();
                if (response && response.responseText) {
                    alert("服务端错误：" + response.responseText + "");
                } else {
                    alert("服务端出错！");
                }
            }
        });
    });

    $(`#pdfPrint`).click(function () {
        showLoading();
        const urlParameters = buildLocationSearchParameters();
        const url = window._server + '/report/pdf/' + window.reportId + urlParameters + `&forPrint=true`;
        const iframe = window.frames['_print_pdf_frame'];
        var data = getChartData();
        showLoading();
        $.ajax({
            url,
            type: 'post',
            data: data,
            xhrFields: {
                responseType: 'blob'
            },
            success: function (result) {
                $("iframe[name='_print_pdf_frame']").on("load", function () {
                    hideLoading();
                    iframe.window.focus();
                    iframe.window.print();
                });
                iframe.window.focus();
                iframe.location.href = window.URL.createObjectURL(result);
            }
        });
    })

    $(`#export-pdf`).click(function () {
        const urlParameters = buildLocationSearchParameters();
        const url = window._server + '/report/pdf/' + window.reportId + urlParameters;
        var data = getChartData();
        showLoading();
        $.ajax({
            url,
            type: 'post',
            data: data,
            xhrFields: {
                responseType: 'blob'
            },
            success: function (result) {
                hideLoading();
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(result);
                a.href = url;
                //设置文件名称
                a.download = new Date().format("yyyy-MM-dd") + '.pdf';
                a.click();
            }
        });
    });

    $(`#export-excel`).click(function () {
        const urlParameters = buildLocationSearchParameters();
        const url = window._server + '/report/excel/' + window.reportId + urlParameters;
        var data = getChartData();
        showLoading();
        $.ajax({
            url,
            type: 'post',
            data: data,
            xhrFields: {
                responseType: 'blob'
            },
            success: function (result) {
                hideLoading();
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(result);
                a.href = url;
                //设置文件名称
                a.download = new Date().format("yyyy-MM-dd") + '.xlsx';
                a.click();
            }
        });
    });

    $('.bolt-horizontalboxlayout').click(function () {
        var button = $($('.bolt-horizontalboxlayout').find("div")[0]);
        var query_form = $('#query_form_' + reportId);
        if (button.hasClass("bolt-query-container-collapseimg-down")) {
            button.addClass("bolt-query-container-collapseimg-up");
            button.removeClass("bolt-query-container-collapseimg-down");
            query_form.slideDown(function () {
                console.info(param_form.height());
                $('.bolt-report-sheet').height($(window).height() - param_form.height() - 45);
            });
        } else {
            button.addClass("bolt-query-container-collapseimg-down");
            button.removeClass("bolt-query-container-collapseimg-up");
            query_form.slideUp();
            $('.bolt-report-sheet').height($(window).height() - 45);
        }
    })
});

window._currentPageIndex = null;
window._totalPage = null;

window.buildLocationSearchParameters = function (exclude) {
    let urlParameters = window.location.search;
    if (urlParameters.length > 0) {
        urlParameters = urlParameters.substring(1, urlParameters.length);
    }
    let parameters = {};
    const pairs = urlParameters.split('&');
    for (let i = 0; i < pairs.length; i++) {
        const item = pairs[i];
        if (item === '') {
            continue;
        }
        const param = item.split('=');
        let key = param[0];
        if (exclude && key === exclude) {
            continue;
        }
        let value = param[1];
        parameters[key] = value;
    }
    if (window.searchFormParameters) {
        for (let key in window.searchFormParameters) {
            if (key === exclude) {
                continue;
            }
            const value = window.searchFormParameters[key];
            if (value) {
                parameters[key] = value;
            }
        }
    }
    let p = '?';
    for (let key in parameters) {
        if (p === '?') {
            p += key + '=' + parameters[key];
        } else {
            p += '&' + key + '=' + parameters[key];
        }
    }
    return p;
};

function buildPrintStyle(paper) {
    const marginLeft = paper.leftMargin;
    const marginTop = paper.topMargin;
    const marginRight = paper.rightMargin;
    const marginBottom = paper.bottomMargin;

    page = paper.pageWidth + 'mm ' + paper.pageHeight + 'mm';

    const style = `
    
        @page {
          size: ${page} ${paper.printOrder};
          border:0;
          padding:0cm;
          margin:0cm;
        }
        
        @page :footer {
            display: none
        }
        @page :header {
            display: none
        }
        
        .bolt-printPaper {
			position: relative;
			padding: 0 0 0 0;
			page-break-after: always;
			overflow-x: hidden;
			overflow: hidden;
		}
		.bolt-printPaper .bolt-printPaper-content {
			position: relative;
		}
    `;
    return style;
};